<template>
  <div class="permission-main">
    <a-card :bordered="false" title="权限列表">
      <div class="operate">
        <a-button type="dashed" style="width: 100%;margin-bottom:10px" icon="plus" @click="doAdd">添加</a-button>
      </div>
      <!-- <a-divider /> -->
      <a-table
        :loading="loading"
        :columns="columns"
        :dataSource="loadData"
        :rowKey="loadData => loadData.id"
        childrenColumnName="auth"
        :pagination="false"
      >
        <span slot="show" slot-scope="text, record">
          <span>{{ record.show == 1 ? '是' : '否' }}</span>
        </span>
        <span slot="icon" slot-scope="text, record">
          <a-icon :type="record.icon" />
        </span>
        <span slot="actions" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="doDel(record)" @cancel="cancel" okText="确认" cancelText="取消">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
      <a-modal
        :title="isadd == true ? '新增权限' : '编辑权限'"
        :width="800"
        v-model="visible"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="mdl">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="权限名称">
            <a-input placeholder="请输入权限名称" v-model="mdl.name" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="权限图标">
            <a-input placeholder="请填写icon名称" v-model="mdl.icon" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="权限标题">
            <a-input placeholder="请填写权限标题" v-model="mdl.title" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否展示">
            <!-- <a-input placeholder="请填写逻辑型" v-model="mdl.show" /> -->
            <a-switch :checked="swcheck" @change="onswitchChange" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="component">
            <a-input placeholder="请填写component" v-model="mdl.component" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="跳转路径">
            <a-input placeholder="(选填)请填写跳转路径" v-model="mdl.redirect" />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="父权限">
            <a-select style="width:100%" defaultValue="" v-model="chooselist" @change="handleChange" :allowClear="true">
              <a-select-option
                v-for="(item, index) in filteredOptions"
                :key="index"
                :value="item"
              >{{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { getNewPermsList, newAddAuth, delAuthInfo, updateAuthInfo } from '@/api/permission'
export default {
  name: 'Permission',
  data () {
    return {
      swcheck: true,
      isadd: false,
      visible: false,
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      form: this.$form.createForm(this),
      mdl: {
        name: '',
        icon: 'smile',
        title: '',
        show: 1,
        component: '',
        redirect: '',
        parentId: 0
      },
      // 表头
      columns: [
        {
          title: 'ID',
          key: 'id',
          dataIndex: 'id'
        },
        {
          title: '权限名称',
          key: 'name',
          dataIndex: 'name'
        },
        {
          title: '父节点',
          key: 'parentId',
          dataIndex: 'parentId'
        },
        {
          title: '图标',
          // dataIndex: 'icon',
          scopedSlots: {
            customRender: 'icon'
          }
        },
        {
          title: '权限标题',
          dataIndex: 'title',
          scopedSlots: {
            customRender: 'title'
          }
        },
        {
          title: '是否展示',
          // dataIndex: 'show',
          scopedSlots: {
            customRender: 'show'
          }
        },
        {
          title: '组件',
          dataIndex: 'component',
          scopedSlots: {
            customRender: 'component'
          }
        },
        {
          title: '重定向',
          dataIndex: 'redirect',
          scopedSlots: {
            customRender: 'redirect'
          }
        },
        {
          title: '操作',
          width: '150px',
          // dataIndex: 'actions',
          scopedSlots: {
            customRender: 'actions'
          }
        }
      ],
      permissionList: [],
      loadData: [
        // {
        //   "id": 2, 自增id
        //   "name": "测试", 名称
        //   "parentId": 0, 节点
        //   "icon": "smile", icon
        //   "title": "测试1", 标题
        //   "show": "show", 逻辑型
        //   "component": "component",
        //   "redirect": "redirect",跳转路径
        //   "auth": [ 权限子类
        //       {
        //           "id": 4,
        //           "name": "测试",
        //           "parentId": 2,
        //           "icon": "smile",
        //           "title": "测试1",
        //           "show": "show",
        //           "component": "component",
        //           "redirect": "redirect"
        //       }
        //     ]
        // }
      ],
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      chooselist: ['该项为添加父权限,如需添加子权限请选择其他父权限'],
      referList: []
    }
  },
  filters: {
    statusFilter (status) {
      const statusMap = {
        1: '正常',
        2: '禁用'
      }
      return statusMap[status]
    }
  },
  created () {
    this.getNewPermsList()
  },
  computed: {
    filteredOptions () {
      return this.permissionList.filter(o => !this.chooselist.includes(o))
    }
  },
  methods: {
    onswitchChange (checked) {
      // console.log(`a-switch to ${checked}`)
      if (checked === true) {
        this.mdl.show = 1
      } else {
        this.mdl.show = 2
      }
    },
    cancel (e) {
      // console.log(e)
      this.$message.info('取消删除')
    },
    handleChange (value) {
      // console.log(`selected ${value}`)
      // this.mdl.parentId = value
      this.chooselist = value
      for (const i in this.referList) {
        if (this.referList[i].title === value) {
          // console.log(this.referList[i])
          this.mdl.parentId = this.referList[i].parentId
        }
      }
    },
    doDel (record) {
      // console.log(record)
      if (record.auth) {
        for (let g = 0; g < record.auth.length; g++) {
          this.delAuthInfo(record.auth[g].id)
        }
        // this.delAuthInfo(record.id)
      } else {
        this.delAuthInfo(record.id)
      }
    },
    delAuthInfo (val) {
      delAuthInfo({
        id: val
      })
        .then(res => {
          console.log('删除返回', res)
          if (res.code === 200) {
            this.$message.success('删除成功!')
            this.getNewPermsList()
            this.handleCancel()
          } else {
            this.$message.info(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$message.error('删除失败!')
        })
    },
    getNewPermsList () {
      this.loading = true
      getNewPermsList({
        page: 1,
        pagesize: 9999
      })
        .then(res => {
          this.loading = false
          this.loadData = []
          this.permissionList = ['该项为添加父权限,如需添加子权限请选择其他父权限']
          this.referList = [
            {
              parentId: 0,
              title: '该项为添加父权限,如需添加子权限请选择其他父权限'
            }
          ]
          // console.log('权限列表', res.data)
          for (const i in res.data) {
            this.loadData.push(res.data[i]) // 属性
            this.permissionList.push(res.data[i].title)
            this.referList.push({
              parentId: res.data[i].id,
              title: res.data[i].title
            })
          }
          // for (const i in this.loadData) {
          //   if (this.loadData[i].data !== null) {
          //     this.loadData[i].children = []
          //     this.loadData[i].children.push(...this.loadData[i].data)
          //   }
          // }
          // console.log('this.permissionList', this.permissionList)
          // console.log('this.loadData', this.loadData)
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    handleCancel (e) {
      this.mdl = {}
      this.mdl.parentId = 0
      this.visible = false
    },
    doAdd () {
      this.isadd = true
      this.visible = true
    },
    handleEdit (record) {
      this.isadd = false
      // console.log(record)
      this.mdl = record
      // this.mdl.parentId = record.id
      this.chooselist = []
      if (record.show === '1') {
        this.swcheck = true
      } else {
        this.swcheck = false
      }
      for (const i in this.referList) {
        if (this.referList[i].parentId === record.parentId) {
          // console.log(this.referList[i])
          this.chooselist.push(this.referList[i].title)
        }
      }
      this.visible = true
    },
    handleOk () {
      if (!this.mdl.id) {
        newAddAuth(this.mdl)
          .then(res => {
            // console.log('新增返回', res)
            if (res.code === 200) {
              this.handleCancel()
              this.$message.success('新增成功!')
              this.getNewPermsList()
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
            this.$message.error('新增失败!')
          })
      } else {
        updateAuthInfo(this.mdl)
          .then(res => {
            // console.log(res)
            if (res.code === 200) {
              this.handleCancel()
              this.$message.success('修改成功!')
              this.getNewPermsList()
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
            this.$message.error('修改失败!')
            this.handleCancel()
          })
      }
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  },
  watch: {}
}
</script>
<style lang="less" scoped>
.permission-main::v-deep {
  width: 100%;

  .ant-table-row.ant-table-row-level-1 {
    background-color: rgb(252, 252, 252);
  }
}
</style>
